package com.xyazm.process.engine.node;

import com.xyazm.process.engine.utils.ProcessorUtils;
import lombok.Getter;

/**
 * 代表一个流程
 * @author xuyou
 * @date 2023年01月31日 21:57
 */
@Getter
public class ProcessorDefinition {

    private String name;

    /**
     * 初始节点
     */
    private ProcessorNode first;

    public ProcessorDefinition() {
    }

    public ProcessorDefinition(ProcessorNode first) {
        setFirst(first);
    }


    public void setFirst(ProcessorNode first) {
        this.first = first;
        // node是否存在环形链条
        if (ProcessorUtils.hasRing(first)) {
            throw new IllegalArgumentException("Processor chain exists ring.");
        }
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toStr() {
        StringBuilder sb = new StringBuilder();
        buildStr(sb, first);
        return sb.toString();
    }

    private void buildStr(StringBuilder sb, ProcessorNode node) {
        for (ProcessorNode processorNode : node.getNextNodes().values()) {
            sb.append(node.getName()).append(" -> ").append(processorNode.getName()).append("\n");
            buildStr(sb, processorNode);
        }
    }


}
